<template>
	<view>
		<u-navbar :border-bottom="false" title="注册" back-icon-color="#ffffff" :background="{background:'#2149c3'}"
			title-color="#ffffff"></u-navbar>
		<view class="bg_fff_color">
			<u-form>
				<view class="padding">
					<view class="cu-avatar xl round margin-xs"
						:style="{backgroundImage:'url('+(cover==''||cover==null?'/static/touxiang.png':cover)+')'}">
					</view>
					<button class="cu-btn round bg-green sm" @click="getUserInfo">微信授权</button>
				</view>
				<!-- <view class="cu-form-group margin-top">
					<view class="title">昵称<text class="required">*</text></view>
					<input maxlength="20" v-model="nickName" placeholder="请填写您的昵称" name="input"></input>
				</view> -->
				<u-form-item label="昵称" labelWidth="130" label-align="right">
					<view class="head_right">
						<u-input v-model="nickName" type="text" :border="false" input-align="right"
							placeholder="请填写您的昵称" />
					</view>
				</u-form-item>
				<!-- <view class="cu-form-group">
					<view class="title">真实姓名</view>
					<input maxlength="10" v-model="realName" placeholder="请填写您的真实姓名" name="input"></input>
				</view> -->
				<u-form-item label="真实姓名" labelWidth="130" label-align="right">
					<view class="head_right">
						<u-input v-model="realName" type="text" :border="false" input-align="right"
							placeholder="请填写您的真实姓名" />
					</view>
				</u-form-item>
				<u-form-item label="性别" labelWidth="130" label-align="right">
					<view class="head_right" @click="isshowsex">
						<view><text>{{sex_hz | filter_sex}}</text>
							<u-select v-model="sex_show" :list="sel_list" @confirm="sexConfirm"></u-select>
						</view>
						<u-icon name="arrow-right" color="#c7c7cc" size="28"></u-icon>
					</view>
				</u-form-item>
				<u-form-item label="生日" labelWidth="130" label-align="right">
					<view class="head_right" @click="birth_click">
						<view>{{birthday}}</view>
						<u-icon name="arrow-right" color="#c7c7cc" size="28"></u-icon>
						<u-picker mode="time" v-model="birthday_show" :params="time_params" @confirm="birthdayConfirm">
						</u-picker>
					</view>
				</u-form-item>
				<u-form-item label="手机号码" labelWidth="130" label-align="right">
					<view class="auto_width">
						<text class="required">*</text>
						<view class="head_right">
							<u-input v-model="telephone" type="number" maxlength="11" :border="false"
								placeholder="请填写手机号码" />
						</view>
						<view class="cu-capsule radius">
							<button class='cu-tag bg-green' open-type="getPhoneNumber"
								@getphonenumber="getPhoneNumber">本机号码</button>
						</view>
					</view>
				</u-form-item>
				<u-form-item label="验证码" labelWidth="130" label-align="right">
					<view class="auto_width">
						<view class="head_right">
							<u-input v-model="code" type="number" maxlength="6" :border="false" placeholder="输入验证码" />
						</view>
						<view class="cu-capsule radius">
							<button @tap="getsmscode" class='cu-btn bg-blue shadow sm'>{{smsbtn.text}}</button>
						</view>
					</view>
				</u-form-item>
				<u-form-item label="邮箱" labelWidth="130" label-align="right">
					<view class="head_right">
						<u-input v-model="email" type="text" :border="false" input-align="right" placeholder="请输入邮箱" />
					</view>
				</u-form-item>
				<u-form-item label="联系地址" labelWidth="130" label-align="right" prop="address">
					<view class="head_right">
						<u-input v-model="address" type="textarea" :border="false" placeholder="请填写您的联系地址" maxlength="100" input-align="right" style="width: 80%;height: 100rpx;text-align: right;" />
					</view>
				</u-form-item>
				<u-form-item label="补充情况" labelWidth="130" label-align="right" prop="address">
					<view class="head_right">
							<u-input v-model="remark" placeholder="请填写您的补充情况" type="textarea" :border="false"  maxlength="100" input-align="right" style="width: 80%;height: 100rpx;text-align: right;" />
					</view>
				</u-form-item>

				<view style="border-top: 1rpx solid #eee;background-color: #ffffff;padding: 1rpx 30rpx;">
					<view class="grace-title" style="margin-top:10rpx;">证明文件（上传合规名片注册额外送30个积分）</view>
					<view class="grace-file-list">
						<view class="add-btn" @tap="addImg" v-if="canAdd">
							<view>+</view>
							<view>添加照片</view>
						</view>
						<view class="items" v-for="(item, index) in imgLists" :key="index">
							<image :src="item" mode="aspectFill" :data-imgurl="item" @tap="showImgs"></image>
							<view class="remove grace-icons icon-remove" @tap="removeImg"
								:id="'grace-items-img-'+index"></view>
						</view>
					</view>
				</view>

				<view class="padding flex flex-direction">
					<button class="cu-btn bg-blue margin-tb-sm lg" @click="send()">提交</button>
				</view>
			</u-form>
		</view>
	</view>
</template>

<script>
	var maxNum = 3,
		_self;
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import Md5 from '@/colorui/jsTools/md5.js';
	export default {
		computed: {
			...mapState(['userInfo', 'hasLogin', 'loginProvider', 'openid'])
		},
		data() {
			return {
				rules: {
					address: [{
						min: 5,
						message: '简介不能少于5个字',
						trigger: 'change'
					}]
				},
				imgLists: [],
				canAdd: true,
				uploadFilePath: '',
				phoneVal: '',
				codeVal: '',
				smsbtn: {
					text: '获取验证码',
					status: false,
					codeTime: 60
				},
				timerId: null,
				code: '',
				nickName: '',
				realName: '',
				telephone: '',
				sex: '',
				birthday: '请选择生日日期',
				email: '',
				address: '',
				remark: '',
				cover: "",
				sessionKey: '',
				scene: '',
				email_show: false,
				sel_list: [{
					value: '0',
					label: '男'
				}, {
					value: '1',
					label: '女'
				}, {
					value: '2',
					label: '未知'
				}],
				sex_show: false,
				sex_hz: 2,
				time_params: {
					year: true,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false
				},
				birthday_show: false
			}
		},
		filters: {
			filter_sex: function(num) {
				if (num == 0) {
					return '男'
				} else if (num == 1) {
					return '女'
				} else if (num == 2) {
					return '未知'
				} else {
					return num
				}
			}
		},
		onLoad(e) {
			_self = this;
			if (e.scene != null && e.scene != '') {
				this.scene = e.scene;
				//console.log(e.scene);
			}
			uni.request({
				url: _self.serverUrl + 'app/getAsData',
				header: {
					"content-type": "application/x-www-form-urlencoded; charset=UTF-8"
				},
				method: 'POST',
				data: {
				},
				success: (r) => {
					//console.log(r.data.data);
					if (r.data.code == 0) {
						uni.login({
							provider: 'weixin',
							success: function(loginRes) {
								// console.log(loginRes);
								if (loginRes.code != undefined) {
									var url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + r.data.data.appid +
										'&secret=' + r.data.data.secret + '&js_code=' +
										loginRes.code + '&grant_type=authorization_code';
									uni.request({
										url: _self.serverUrl + 'app/sendUrl',
										header: {
											"content-type": "application/x-www-form-urlencoded; charset=UTF-8"
										},
										data: {
											url: url
										},
										method: 'POST',
										success(res) {
											//console.log(res.data);
											if (res.data.code == 0) {
												_self.sessionKey = JSON.parse(res.data.data).session_key;
											}
										}
									});
								}
							}
						});
					}
				}
			})
		},
		methods: {
			...mapMutations(['login', 'logout', 'setOpenid', 'setProvider']),
			addImg: function() {
				var num = maxNum - _self.imgLists.length;
				if (num < 1) {
					return false;
				}
				uni.showLoading({
					title: ""
				});
				uni.chooseImage({
					count: num,
					sizeType: ['compressed'],
					success: function(res) {
						_self.imgLists = _self.imgLists.concat(res.tempFilePaths);
						if (_self.imgLists.length >= maxNum) {
							_self.canAdd = false;
						}
						uni.hideLoading();
					},
					fail: function() {
						uni.hideLoading();
					}
				});
			},
			removeImg: function(e) {
				var index = e.currentTarget.id.replace('grace-items-img-', '');
				_self.imgLists.splice(index, 1);
				_self.imgLists = _self.imgLists;
				if (_self.imgLists.length < maxNum) {
					_self.canAdd = true;
				}
			},
			showImgs: function(e) {
				var currentImg = e.currentTarget.dataset.imgurl;
				uni.previewImage({
					urls: this.imgLists,
					current: currentImg
				})
			},
			getUserInfo: function(e) {
				uni.getUserProfile({
					desc: 'Wexin',
					success: function(infoRes) {
						//console.log(infoRes);
						_self.cover = infoRes.userInfo.avatarUrl;
						_self.nickName = infoRes.userInfo.nickName;
						_self.sex_hz = infoRes.userInfo.gender == 1 ? '0' : infoRes.userInfo.gender == 2 ?
							'1' : '2';
					},
				});
			},
			getPhoneNumber: function(e) {
				if (e.detail.iv == null || e.detail.iv == '') {
					// console.log('授权失败'); 
					return;
				}
				var iv = e.detail.iv;
				var encryptedData = e.detail.encryptedData;
				uni.request({
					url: _self.serverUrl + 'app/getPhoneDecode',
					header: {
						"content-type": "application/x-www-form-urlencoded; charset=UTF-8"
					},
					method: 'POST',
					data: {
						iv: iv,
						encryptedData: encryptedData,
						sessionKey: _self.sessionKey
					},
					success: (r) => {
						// console.log(r);
						if (r.data.code == 0) {
							_self.telephone = JSON.parse(r.data.msg).phoneNumber;
						}
					}
				})
			},
			send() {
				/* uni.showToast({ title: "系统升级中...", icon: "none" });
				return; */
				if (this.nickName.length < 1) {
					uni.showToast({
						title: "昵称不能为空",
						icon: "none"
					});
					return;
				}
				if (this.telephone.length < 1) {
					uni.showToast({
						title: "手机号不能为空",
						icon: "none"
					});
					return;
				}
				var reg = /^1[0-9]{10,10}$/;
				if (!reg.test(this.telephone)) {
					uni.showToast({
						title: "手机号格式不正确",
						icon: "none"
					});
					return;
				}
				if (this.code.length < 1) {
					uni.showToast({
						title: "验证码不能为空",
						icon: "none"
					});
					return;
				}
				if (this.telephone != this.phoneVal || this.code != this.codeVal) {
					uni.showToast({
						title: "验证码不正确",
						icon: "none"
					});
					return;
				}
				uni.showLoading({});
				if (this.imgLists.length > 0) {
					this.uploadFiles();
				} else {
					this.submitMember();
				}
			},
			uploadFiles(f) {
				var i = f ? f : 0;
				uni.uploadFile({
					url: this.serverUrl + 'app/upload',
					header: {
						"content-type": "application/x-www-form-urlencoded; charset=UTF-8"
					},
					filePath: this.imgLists[i],
					name: 'file',
					method: "POST",
					formData: {
						username: "",
					},
					success: (r) => {
						// console.log(r);
						var rdata = JSON.parse(r.data);
						this.uploadFilePath += rdata.url + ";";
					},
					fail: (r) => {
						uni.showToast({
							title: "上传失败",
						})
					},
					complete: (r) => {
						i++;
						if (i == this.imgLists.length) {
							this.uploadFilePath = this.uploadFilePath.substring(0, this.uploadFilePath.length -
								1);
							this.submitMember();
						} else {
							f = i;
							this.uploadFiles(f);
						}
					}
				});
			},
			submitMember: function() {
				var timestamp = new Date().getTime();
				uni.request({
					url: this.serverUrl + 'app/addMember',
					header: {
						"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
						"token": timestamp + Md5.md5('mude2020' + timestamp)
					},
					method: 'POST',
					data: {
						nickName: this.nickName,
						realName: this.realName,
						telephone: this.telephone,
						cover: this.cover,
						sex: this.sex_hz,
						birthday: this.birthday,
						email: this.email,
						address: this.address,
						remark: this.remark,
						openId: this.openid,
						userType: this.scene == '' ? 1 : 2,
						integralCount: 10,
						pid: this.scene,
						card: this.uploadFilePath,
					},
					success: (r) => {
						if (r.data.code == 1) {
							this.login(r.data.data);
							uni.showLoading({
								title: '提交成功'
							})
							setTimeout(function() {
								uni.switchTab({
									url: '/pages/index/index'
								})
							}, 800)
						}
					},
					complete: (r) => {
						uni.hideLoading();
					}
				})
			},
			getsmscode: function() {
				if (this.smsbtn.status == true) {
					return false;
				}
				var reg = /^1[0-9]{10,10}$/;
				if (!reg.test(this.telephone)) {
					uni.showToast({
						title: "请先填写正确的手机号",
						icon: "none"
					});
					return;
				}
				uni.showLoading({});
				var timestamp = new Date().getTime();
				uni.request({
					url: this.serverUrl + 'app/sendSmsCode',
					header: {
						"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
						"token": timestamp + Md5.md5('mude2020' + timestamp)
					},
					method: 'POST',
					data: {
						telephone: this.telephone,
					},
					success: (r) => {
						if (r.data.code == 0) {
							console.log(r.data.codeVal);
							if (r.data.type != null && r.data.type == '0') {
								uni.showToast({
									icon: "none",
									title: "手机号已被注册"
								})
								return;
							}
							if (r.data.type != null && r.data.type == '1') {
								uni.showToast({
									icon: "none",
									title: "手机号发送验证码次数今日已达上限"
								})
								return;
							}
							var temp = JSON.parse(r.data.data);
							if (temp.Code != null && temp.Code != 'OK') {
								uni.showToast({
									icon: "none",
									title: "获取验证码失败"
								})
								return;
							}
							/* if(r.data.data!=null && r.data.data!='1000'){
								uni.showToast({
									icon:"none",
									title:"获取验证码失败"
								})
								return;
							} */
							this.phoneVal = this.telephone;
							this.codeVal = r.data.codeVal;
							this.smsbtn.status = true; // 短信发送成功后
							this.timerId = setInterval(() => {
									var codeTime = this.smsbtn.codeTime;
									codeTime--;
									this.smsbtn.codeTime = codeTime;
									this.smsbtn.text = codeTime + "s";
									if (codeTime < 1) {
										clearInterval(this.timerId);
										this.smsbtn.text = "重新获取";
										this.smsbtn.codeTime = 60;
										this.smsbtn.status = false;
									}
								},
								1000);
							return false;

						}
					},
					complete: (res) => {
						uni.hideLoading();
					}
				})


			},
			open_email() {
				this.email_show = true;
			},
			isshowsex() {
				this.sex_show = true;
				console.log(this.sex_hz)
			},
			sexConfirm(e) {
				this.sex_hz = e[0].value;
			},
			birth_click() {
				this.birthday_show = true
			},
			birthdayConfirm(e) {
				this.birthday = e.year + "-" + e.month + "-" + e.day;
			}
		}
	}
</script>

<style lang="scss">
	@import "../../graceUI/graceIcons.css";

	/* 文件选择及预览 */
	.grace-file-list {
		display: -webkit-box;
		display: -webkit-flex;
		display: flex;
		-webkit-flex-wrap: wrap;
		flex-wrap: wrap;
	}

	.grace-file-list .add-btn {
		width: 31.3%;
		height: 210rpx;
		margin: 5px 1%;
		background: #F3F4F5;
	}

	.grace-file-list .add-btn view {
		font-size: 28rpx;
		height: 40rpx;
		margin-top: 5px;
		line-height: 40rpx;
		text-align: center;
		color: #999999;
		width: 100%;
	}

	.grace-file-list .add-btn view:first-child {
		font-size: 120rpx !important;
		height: 80rpx;
		line-height: 80rpx;
		margin: 20rpx 0;
	}

	.grace-file-list .items {
		width: 31.3%;
		position: relative;
		overflow: hidden;
		height: 210rpx;
		margin: 5px 1%;
		font-size: 0;
		background: #F3F4F5;
	}

	.grace-file-list .items image {
		width: 100%;
	}

	.grace-file-list .items .remove {
		width: 50rpx;
		height: 50rpx;
		line-height: 50rpx;
		text-align: center;
		font-size: 40rpx;
		position: absolute;
		z-index: 1;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		color: #FFFFFF;
	}

	.required {
		color: red;
	}

	.padding {
		text-align: center;
	}

	.cu-form-group .title {
		width: 170rpx;
	}

	.head_right {
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}

	.bg_fff_color {
		background-color: #FFFFFF;
		padding: 0rpx 40rpx 0rpx 45rpx;
	}

	.user_photo {
		padding: 0px 35rpx 20rpx 40rpx;

		.grace-title {
			font-size: 28rpx;
			color: #555555;
		}
	}

	.zdytjbc button {
		background-image: linear-gradient(#2149c3,
				#2149c3),
			linear-gradient(90deg,
				#1f69ff 0%,
				#7059ff 100%);
		background-blend-mode: normal,
			normal;
		border-radius: 10rpx;
		font-size: 30rpx;
		color: #ffffff;
	}

	.input_content {
		padding: 0rpx 30rpx;
	}

	.auto_width {
		display: flex;
		justify-content: space-around;
		align-items: center;
	}
</style>
